#include "jack_task.h"
#include "kernel/agv/agv_entity.h"
#include <QString>

namespace application {
namespace task {

JackTask::JackTask(
    bool raise,
    std::shared_ptr<vehicle::VehicleService> vehicleService,
    std::shared_ptr<kernel::ILogger> logger,
    const std::string& operationStation,
    int waitTimeSeconds)
    : SubTaskBase(logger)
    , m_raise(raise)
    , m_vehicleService(vehicleService)
    , m_operationStation(operationStation)
    , m_waitTimeSeconds(waitTimeSeconds)
{
}

kernel::task::TaskStage JackTask::init(TaskContext& ctx)
{
    // 检查前置条件
    if (!m_vehicleService) {
        return finishWithError(ctx, "VehicleService not available");
    }

    if (!ctx.agv) {
        return finishWithError(ctx, "No AGV assigned to jack task");
    }

    // 如果指定了操作站点，检查AGV是否在该站点
    if (!m_operationStation.empty()) {
        std::string currentStation = ctx.agv->getCurrentStation();

        bool atStation = (currentStation == m_operationStation);

        // 检查是否导航任务完成（参考三方代码 task_jack.cpp:34-35）
        auto navStatus = ctx.agv->getNavStatus();
        bool navComplete = (navStatus == kernel::agv::NavStatus::Completed ||
                           navStatus == kernel::agv::NavStatus::Canceled);

        if (!atStation || !navComplete) {
            logDebug("Waiting for AGV to arrive at jack operation station: " +
                    m_operationStation + ", current: " + currentStation);
            // 继续等待
            return kernel::task::TaskStage::Init;
        }
    }

    logInfo("Starting jack task for AGV " +
            std::to_string(ctx.agv->getNumber()) +
            " (" + (m_raise ? "raise" : "lower") + ")");

    // 下发顶升命令
    bool success = m_vehicleService->controlJack(
        ctx.agv->getNumber(),
        m_raise
    );

    if (!success) {
        return finishWithError(ctx, "Failed to send jack command");
    }

    m_commandSent = true;
    m_commandTime = std::chrono::system_clock::now();

    logInfo("Jack command sent successfully, waiting " +
            std::to_string(m_waitTimeSeconds) + " seconds");

    // TODO: 清除 finalOperation（参考三方代码 task_jack.cpp:39）
    // ctx.agv->clearFinalOperation();

    return kernel::task::TaskStage::Running;
}

kernel::task::TaskStage JackTask::run(TaskContext& ctx)
{
    if (!m_commandSent) {
        return finishWithError(ctx, "Jack command not sent");
    }

    // 等待指定时间（参考三方代码 task_jack.cpp:46）
    if (isWaitTimeElapsed()) {
        logInfo("Jack task wait time elapsed, task complete");
        return kernel::task::TaskStage::Cleanup;
    }

    // 继续等待
    return kernel::task::TaskStage::Running;
}

kernel::task::TaskStage JackTask::cleanup(TaskContext& ctx)
{
    logDebug("Jack task cleanup");

    // 顶升任务无需特殊清理
    return kernel::task::TaskStage::Finished;
}

bool JackTask::isWaitTimeElapsed() const
{
    auto now = std::chrono::system_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(
        now - m_commandTime
    );

    return elapsed.count() >= m_waitTimeSeconds;
}

} // namespace task
} // namespace application
